<?php


namespace app\admin\controller;


use app\common\controller\Common;
use app\index\controller\Base;
use think\Db;
use think\Exception;
use think\Request;
use think\Session;
use think\Validate;

class Agent extends Base
{
    //删除代理商
    public function delAgent(){
        try{
            $id = $_POST['id'];
            $res = Db::name("admin_agent")->where(['id'=>['in',$id]])->update(['is_del'=>1]);
            if(empty($res)){
                throw new Exception("删除失败");
            }
            //清空代理的区域
            Db::name("admin_agent_city")->where(['agent_id'=>['in',$id]])->delete();
            $name = Db::name("admin_agent")->where(['id'=>['in',$id]])->value("name");
            $common = new Common();
            $log['operator'] = Session::get("user_name");
            $log['operator_id'] = Session::get("id");
            $log['addtime'] = time();
            $log['ip'] = request()->ip();
            $log['remark'] = "管理员【" . Session::get("user_name") . "】删除代理商账号【".$name."】";
            $log['controller'] = "Agent";
            $log['methods'] = "delAgent";

            $common->addLog($log);
            $black['code'] = 0;
            $black['msg'] = "删除成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    public function index(){
        //权限查询
        $common = new Common();
        $powerList = $common->showpower();
        $this->assign("powerList",$powerList);

        $keyword = '';
        $phone = '';
        $time = '';
        $area = '';
        $wechat = "";
        $where['is_del'] = 0;

        if(!empty($_GET['keyword'])){
            $where['name'] = ['like',"%".$_GET['keyword']."%"];
            $keyword = $_GET['keyword'];
        }
        if(!empty($_GET['phone'])){
            $where['phone'] = ['like',"%".$_GET['phone']."%"];
            $phone = $_GET['phone'];
        }
        if(!empty($_GET['time'])){
            $time = $_GET['time'];
            $serach = explode(' - ',$time);
            $starttime = strtotime($serach[0]);
            $endttime = strtotime($serach[1]." 23:59:59");
            $where['addtime'] = [["gt",$starttime],["elt",$endttime]];
        }
        if(!empty($_GET['area'])){
            //获取区域信息
            $where1['name'] = ['like',"%".$_GET['area']."%"];
            $where1['level'] = ['elt',"3"];
            $region = Db::name("admin_region")->field("id,level,name,code")->where($where1)->select();
            $region_val = array_column($region,"id");
            $where['agency'] = ['in',$region_val];
            //查询代理区域
            $cityWhere['province'] = ['in',$region_val];
            $cityWhere['city'] = ['in',$region_val];
            $cityWhere['area'] = ['in',$region_val];
            $agent_city = Db::name("admin_agent_city")->whereOr($cityWhere)->field("agent_id")->select();
            $agent_city = array_column($agent_city,"agent_id");
            $agent_city = array_unique($agent_city);
            $whereOr['id'] = ['in',$agent_city];
            $area = $_GET['area'];
        }

        if(!empty($_GET['type'])){
            //根据平台区分
            $thisWechat = Session::get("thisWechat");
            if(!empty($thisWechat)){
                $where['uniacid'] = $thisWechat['id'];
            }
            //根据平台区分end

            $page = empty($_GET['page'])?1:$_GET['page'];
            $limit = empty($_GET['limit'])?10:$_GET['limit'];
            $start = ($page-1)*$limit;

            //链表查询
            $data = Db::name("admin_agent")->order("id desc")->where($where);
            if(!empty($whereOr)){
                $data = $data->whereOr($whereOr);
            }
            $list = $data->limit($start,$limit)->select();

            //统计数据
            $data = Db::name("admin_agent")->order("id desc")->where($where);
            if(!empty($whereOr)){
                $data = $data->whereOr($whereOr);
            }
            $count = $data->count();

            //统计终端数量
            foreach ($list as $k => $v) {
                $area = Db::name("admin_agent_city")->where(['agent_id'=>$v['id']])->field("id,area")->select();
                //所代理区域
                $list[$k]['count'] = count($area);

                $list[$k]['addtime'] = date("Y-m-d H:i:s",$v['addtime']);
                //查询代理城市
                //$list[$k]['province_name'] = Db::name("admin_region")->where(['id' => $v['area']])->value('name');
            }
            $black['code'] = 0;
            $black['data'] = $list;
            $black['count'] = $count;
            return $black;

        }

        $assign = [
            "keyword"=>$keyword,
            "time"=>$time,
            "area"=>$area,
            "phone"=>$phone,
            "wechat"=>$wechat
        ];
        $this->assign($assign);

        return $this->fetch('index');
    }


    //添加视图
    public function addAgent()
    {
        //$this->assign('province',$province);
//        return view("addAgent");
        if (!empty($_POST)) {
            //开启事物
            Db::startTrans();
            try {
                $common = new Common();
                if (!empty($_POST['id'])) {
                    $rule = [
                        ["name", "require", "请填写帐号"],
                        ["phone", "require", "请填写手机号码"],
                    ];
                } else {
                    $rule = [
                        ["name", "require", "请填写帐号"],
                        ["password", "require", "请填写密码"],
                        ["password1", "require", "请填写确认密码"],
                        ["phone", "require", "请填写手机号码"],
                    ];
                }
                $validate = new Validate($rule);
                $data = $this->request->post();
                if (!$validate->check($data)) {
                    throw new Exception($validate->getError());
                }
                if ($_POST['password1'] != $_POST['password']) {
                    throw new Exception("两次输入的密码不一致");
                } else {
                    unset($_POST['password1']);
                    if (!empty($_POST['password'])) {
                        $_POST['password'] = md5($_POST['password']);
                    }
                }
                if (!empty($_POST['phone'])) {
                    $is_mobile = $common->is_mobile($_POST['phone']);
                    if (!$is_mobile) {
                        throw new Exception("手机号码有误");
                    }
                }
                if (!empty($_POST['id'])) {
                    if (empty($_POST['password'])) {
                        unset($_POST['password']);
                    }
                    $accountWhere['name'] = $_POST['name'];
                    $accountWhere['table'] = "admin_agent";
                    $accountWhere['table_id'] = ['neq', $_POST['id']];
                    $agentWhere['phone'] = $_POST['phone'];
                    $agentWhere['id'] = ['neq', $_POST['id']];
                } else {
                    $accountWhere['name'] = $_POST['name'];
                    $agentWhere['phone'] = $_POST['phone'];
                }
                //判断账号是否已存在
                $isname = Db::name("admin_account_data")->where($accountWhere)->value("id");
                //判断手机号是否已存在
                $isphone = Db::name("admin_agent")->where($agentWhere)->value("id");
                if (!empty($isname)) {
                    throw new Exception("该账号已存在，请勿重复注册");
                }
                if (!empty($isphone)) {
                    throw new Exception("该手机号已注册");
                }
                $agency = "";
                foreach ($_POST as $k => $v) {
                    if (strpos($k, 'ayuiTreeCheck')) {
                        unset($_POST[$k]);
                        $agency .= $v . ",";
                    }
                }
                $agency = trim($agency, ",");
                if (empty($agency)) {
                    throw new Exception("请选择代理城市");
                }
                $_POST['agency'] = $agency;
                //城市分区
                $checkedData = $_POST['checkedData'];
                unset($_POST['checkedData']); //去除多余字段
                $id = empty($_POST['id']) ? '' : $_POST['id'];
                $data = $_POST;

                //根据平台区分
                $thisWechat = Session::get("thisWechat");
                $data['uniacid'] = $thisWechat['id'];
                //根据平台区分end

                if (empty($id)) {
                    $data['addtime'] = time();
                    $data['add_id'] = Session::get("id");
                    $agent = Db::name("admin_agent")->insertGetId($data);
                    //记录账号信息
                    $AccountData['name'] = $_POST['name'];
                    $AccountData['password'] = $_POST['password'];
                    $AccountData['addtime'] = time();
                    $AccountData['add_id'] = Session::get("id");
                    $AccountData['phone'] = $_POST['phone'];
                    $AccountData['table'] = "admin_agent";
                    $AccountData['table_id'] = $agent;
                    $common->addAccountData($AccountData);
                } else {
                    $data['updatetime'] = time();
                    $data['update_id'] = Session::get("id");
                    Db::name("admin_agent")->where(['id' => $id])->update($data);
                    //记录账号信息
                    $AccountData['name'] = $_POST['name'];
                    if (!empty($_POST['password'])) {
                        $AccountData['password'] = $_POST['password'];
                    }
                    $AccountData['addtime'] = time();
                    $AccountData['add_id'] = Session::get("id");
                    $AccountData['phone'] = $_POST['phone'];
                    $common->updateAccountData($AccountData, "admin_agent", $id);
                    $agent = $id;
                }
                //查询代理的区域
                $oldcity = [];
                if (!empty($id)) {
                    $oldcity = Db::name("admin_agent_city")->where(['agent_id' => $id])->field("id,area")->select();
                    $oldcity = array_column($oldcity, "area");
                }
                $area = "";
                $checkedData = json_decode($checkedData, true);
                if (!empty($id)) {
                    $newcity = [];
                    foreach ($checkedData as $k => $v) {
                        foreach ($v['children'] as $k1 => $v1) {
                            foreach ($v1['children'] as $k2 => $v2) {
                                $newcity[] = $v2['id'];
                            }
                        }
                    }
                    foreach ($oldcity as $k=>$v){
                        if(!in_array($v,$newcity)){
                            //删除区域代理商
                            Db::name("admin_agent_city")->where(['agent_id' => $id,'area'=>$v])->delete();
                        }
                    }
                }
                foreach ($checkedData as $k => $v) {
                    foreach ($v['children'] as $k1 => $v1) {
                        foreach ($v1['children'] as $k2 => $v2) {
                            $cityDate['agent_id'] = $agent;
                            $cityDate['province'] = $v['id'];
                            $cityDate['city'] = $v1['id'];
                            $cityDate['area'] = $v2['id'];
                            $cityDate['addtime'] = time();
                            $cityDate['add_id'] = Session::get("id");
                            if (!empty($id)) {
                                //判断该区域是否被代理
                                $agentcityWhere['a.agent_id'] = ['neq', $agent];
                            }
                            //判断该区域是否被代理
                            $agentcityWhere['a.area'] = $v2['id'];
                            $thisWechat = Session::get("thisWechat");
                            $agentcityWhere['b.uniacid'] = $thisWechat['id'];
                            $cityId = Db::name("admin_agent_city")->alias("a")
                                ->join("admin_agent b","a.agent_id = b.id")->where($agentcityWhere)->value('a.id');
                            if (!empty($cityId)) {
                                throw new Exception($v2['title'] . "已被代理");
                            }
                            $area .= $v2['title'] . ",";
                            if (!empty($id)) {
                                if (in_array($v2['id'], $oldcity)) {
                                    continue;
                                } else {
                                    Db::name("admin_agent_city")->insert($cityDate);
                                }
                            } else {
                                Db::name("admin_agent_city")->insert($cityDate);
                            }
                        }
                    }
                }
                $log['operator'] = Session::get("user_name");
                $log['operator_id'] = Session::get("id");
                $log['addtime'] = time();
                $log['ip'] = request()->ip();
                $log['controller'] = "Agent";
                $log['methods'] = "addAgent";
                if (!empty($id)) {
                    $log['remark'] = "管理员【" . Session::get("user_name") . "】修改代理商" . $_POST['name'] . "代理城市" . trim($area, ",");
                    $common->addLog($log);
                }else{
                    $log['remark'] = "管理员【" . Session::get("user_name") . "】添加代理商" . $_POST['name'] . "代理城市" . trim($area, ",");
                    $common->addLog($log);
                }
                Db::commit();
                $black['code'] = 0;
                $black['msg'] = "操作成功";
            } catch (Exception $e) {
                Db::rollback();
                $black['code'] = 202;
                $black['msg'] = $e->getMessage() . $e->getLine();
            }
            return $black;
        } else {
            if (!empty($_GET['id'])) {
                $id = $_GET['id'];
                $detail = Db::name("admin_agent")->where(['id' => $id])->find();
                $assign['detail'] = $detail;
                $this->assign($assign);
                return $this->fetch('editAgent');
            } else {
                return $this->fetch('addAgent');
            }
        }
    }


    //启用禁用操作
    public function clickStatus()
    {
        try {
            $common = new Common();
            $data['status'] = $_POST['status'];
            Db::name("admin_agent")->where(['id' => $_POST['id']])->update($data);
            $log['operator'] = Session::get("user_name");
            $log['operator_id'] = Session::get("id");
            $log['addtime'] = time();
            $log['ip'] = request()->ip();
            $log['controller'] = "Agent";
            $log['methods'] = "clickStatus";
            $name = Db::name("admin_agent")->where(['id' => $_POST['id']])->value("name");
            if ($_POST['status'] == 1) {
                $log['remark'] = "管理员【" . Session::get("user_name") . "】开启代理商【".$name."】";
            } else {
                $log['remark'] = "管理员【" . Session::get("user_name") . "】禁用代理商【".$name."】";
            }
            $common->addLog($log);
            $black['code'] = 0;
            $black['msg'] = "操作成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
        /*try {
            $common = new Common();
            $data['status'] = $_POST['status'];
            Db::name("admin_agent_city")->where(['id' => $_POST['id']])->update($data);
            $log['operator'] = Session::get("user_name");
            $log['operator_id'] = Session::get("id");
            $log['addtime'] = time();
            $log['ip'] = request()->ip();

            $area = Db::name("admin_agent_city")->where(['id' => $_POST['id']])->value("area");
            $name = Db::name("admin_region")->where(['id' => $area])->value("name");

            if ($_POST['status'] == 1) {
                $log['remark'] = "管理员【" . Session::get("user_name") . "】开启代理区域" . $name;
            } else {
                $log['remark'] = "管理员【" . Session::get("user_name") . "】关闭代理区域" . $name;
            }
            $common->addLog($log);
            $black['code'] = 0;
            $black['msg'] = "操作成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;*/
    }
}